package com.sky.controller.admin;

import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController()
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "文件上传接口")
public class CommonController {

    @Value("${image.path}")
    private String imagePath;

    @Value("${image.requestPath}")
    private String imageRequestPath;


    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {

        String originalFilename = file.getOriginalFilename();

        log.info("上传原始文件名：{}", originalFilename);

        //获取文件后缀名
        if (originalFilename == null) {
            throw new RuntimeException("文件上传为空！");
        }

        originalFilename = originalFilename.substring(originalFilename.lastIndexOf("."));

        //存储唯一标识文件名 + 后缀名
        String newFileName = UUID.randomUUID() + originalFilename;
        log.info("上传原新文件名：{}", newFileName);

        //设置文件上传的位置
        try {
            file.transferTo(new File(imagePath + newFileName));
            //返回路径
            return Result.success(imageRequestPath + newFileName);

        } catch (IOException e) {
            log.error("文件上传失败");
            throw new RuntimeException(e);
        }


    }

}
